package com.caregiver.watch.business.notice.service.impl;

import com.caregiver.watch.business.notice.dao.JPushUserBindingDao;
import com.caregiver.watch.business.notice.model.dto.BindPushIdParam;
import com.caregiver.watch.business.notice.model.dto.UnbindPushIdParam;
import com.caregiver.watch.business.notice.model.po.JPushUserBinding;
import com.caregiver.watch.business.notice.service.PushService;
import com.caregiver.watch.business.user.utils.UserInfoUtils;
import com.caregiver.watch.common.exception.BaseException;
import com.caregiver.watch.thirdparty.service.JPushService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Objects;

import static com.caregiver.watch.common.constant.NumberConstants.ZERO;

/**
 * @program: caregiver-watch
 * @author: 疆戟
 * @create: 2025-10-05 15:17
 */
@AllArgsConstructor
@Service
@Slf4j
public class PushServiceImpl implements PushService {

    private final JPushUserBindingDao jPushUserBindingDao;

    @Override
    public Boolean bindPushId(BindPushIdParam param) {
        String registrationId = param.getRegistrationId();
        if (StringUtils.isBlank(registrationId)) {
            throw new BaseException("极光推送注册ID不能为空");
        }
        Long userId = UserInfoUtils.getUserId();
        JPushUserBinding po = param.toPo(userId);
        // 如果出现冲突重试2次
        for (int i = 0; i < 3; i++) {
            try {
                // 删除之前的绑定信息
                jPushUserBindingDao.deleteByRegistrationId(registrationId);
                return jPushUserBindingDao.insert(po) > ZERO;
            } catch (DuplicateKeyException e) {
                // 这里要捕获唯一索引冲突的异常
                log.error("极光推送注册ID{}已存在", param.getRegistrationId(), e);
            }  catch (Exception e) {
                log.error("极光推送用户设备绑定关系数据插入失败", e);
                return Boolean.FALSE;
            }
        }
        return Boolean.FALSE;
    }

    @Override
    public Boolean unbindPushId(UnbindPushIdParam param) {
        String registrationId = param.getRegistrationId();
        if (StringUtils.isBlank(registrationId)) {
            throw new BaseException("极光推送注册ID不能为空");
        }
        return jPushUserBindingDao.deleteByRegistrationId(registrationId) > ZERO;
    }

    @Override
    public Boolean unbindPushId(Long userId) {
        if (Objects.isNull(userId)) {
            return Boolean.FALSE;
        }
        return jPushUserBindingDao.deleteByUserId(userId) > ZERO;
    }


}
